<?php

namespace app\admin\controller;
class ResearchCopy extends base
{
    //前置方法
    protected $beforeActionList = [
        'map' => ['only' => 'index,read'],
    ];

    /**
     * 搜索
     */
    protected function map()
    {
        if ($this->request->isGet()) {
            $data = $this->request->param();
            $this->datas = array();
            if (!empty($data['start_time']) && !empty($data['end_time']) && (strtotime($data['start_time']) < strtotime($data['end_time']))) {
                $this->datas ['create_time'] = [
                    ['>', strtotime($data['start_time'])],
                    ['<', strtotime($data['end_time'])]
                ];
            }
            if (!empty($data['cid'])) {
                $this->datas ['cid'] = $data['cid'];
            }
            if (!empty($data['username'])) {
                 $this->datas ['username'] = ['like', '%' . $data['username'] . '%'];
            }
            $this->datas['lang'] = cookie('think_var_admin');
        }
    }


    public function add()
    {

        $ss = allow_release_arctype(0, array($this->request->controller()));
        $this->assign('ss', $ss);

        return $this->fetch('add',
            ['addcid' => $this->request->param('addcid'),]
        );
    }

    public function edit($id)
    {
        if (intval($id) < 1) {
            $this->error('数据错误');
        }


        //清理缓存
        cache($this->request->controller() . $id, null);
        $data = $this->model->get($id);
        $data['starttime'] = date("Y-m-d H:i:s", $data['starttime']);
        $data['dateline'] = date("Y-m-d H:i:s", $data['dateline']);
        $rqdata = db('Research_question_copy')->where(array('rid' => $id))->order('id asc')->select();
        $useqids = $list = array();
        foreach ($rqdata as $v) {
            $useqids[] = $v['id'];
            $answerobj = db('Research_answer_copy')->where(array('qid' => $v['id']))->order('id asc')->select();
            $v['Ranswer'] = $answerobj;
            $list[] = $v;
        }

        $ss = allow_release_arctype(0, array($this->request->controller()));
        $this->assign('ss', $ss);

        $this->assign('list', $list);
        $this->assign('data', $data);
        return $this->fetch();
    }

    /**
     * 保存
     */
    public function save()
    {

        if (!$this->request->isPost()) {
            return ajax_info('请求失败');
        }
        $useqids = $useaids = $updateqids = $updateaids = $nouseaid = $nouseqid = array();

        $data = $this->request->post();
        if (empty($data['cid']) ){
            return ajax_info('添加错误','u');
            exit();

        }

        if(empty($data['title'])) {
//            return ajax_info('请填写标题');
//            exit();
        }

        if (empty($data['question']) || empty($data['option'])) {
            return ajax_info('请填写问题的题目');
            exit();
        }

        $question = isset($data['question']) ? $data['question'] : array();
        $answer = isset($data['answer']) ? $data['answer'] : array();
        $oldquestion = isset($data['oldquestion']) ? $data['oldquestion'] : array();
        $option = isset($data['option']) ? $data['option'] : array();
        $rid = isset($data['id']) ? intval($data['id']) : 0;
        $ismulti = isset($data['ismulti']) ? $data['ismulti'] : array();
        $qids = isset($data['qid']) ? $data['qid'] : array();
        $aids = isset($data['oid']) ? $data['oid'] : array();
        $point = isset($data['point']) ? $data['point'] : array();

        $data['starttime'] = strtotime($data['starttime']);
        $data['dateline'] = strtotime($data['dateline']);

//        foreach ($answer as $i =>$kk){
//             $kk = str_replace('，',',',$kk);
//             $kk = explode(",",$kk);
//            sort($kk);
//            $kk = array_unique($kk);
//            $kk = implode(',',$kk);
//            $answer[]=$kk;
//    }

        //修改
        if (!empty($data['id'])) {

            $rqdata = db('Research_question_copy')->where(array('rid' => $rid))->order('id asc')->select();
            foreach ($rqdata as $v) {
                $useqids[] = $v['id'];
                $answerobj = db('Research_answer_copy')->where(array('qid' => $v['id']))->order('id asc')->select();
                $v['answer'] = $answerobj;
                foreach ($answerobj as $a) {
                    $useaids[] = $a['id'];
                }
            }

            $this->model->allowField(true)->save($data, ['id' => $rid]);

            //删除的题目
            foreach ($qids as $k => $v) {
                $updateqids[] = $qids[$k];
            }


            foreach ($question as $k => $q) {
                if (!isset($option[$k]) || (isset($option[$k]) && empty($option[$k])) || empty($q) || !isset($k)) continue;
                $qdata = array('rid' => $rid,'point'=>$point[$k], 'answer' => strtoupper($answer[$k]), 'name' => htmlspecialchars($q), 'type' => isset($ismulti[$k]) ? intval($ismulti[$k]) : 0);
                if ($qids[$k]) {
                    $qdata['id'] = $qids[$k];
                    db('Research_question_copy')->update($qdata);
                    foreach ($option[$k] as $i => $v) {

                        if (!isset($aids[$k][$i])) continue;
                        $adata = array('qid' => $qids[$k], 'question' => $oldquestion[$k][$i], 'name' => htmlspecialchars($v));
                        if (empty($aids[$k][$i])) {
                            db('Research_answer_copy')->insert($adata);
                        } else {
                            $adata['id'] = $aids[$k][$i];
                            db('Research_answer_copy')->update($adata);
                            $updateaids[] = $aids[$k][$i];
                        }
                    }
                } else {
                    if (db('Research_question_copy')->insert($qdata)) {
                        $qid = db('Research_question_copy')->getLastInsID();
                        foreach ($option[$k] as $kk => $v) {
//                            if (empty($v)) continue;
                            $adata = array('qid' => $qid, 'question' => $oldquestion[$k][$kk], 'name' => htmlspecialchars($v));
                            $aid = db('Research_answer_copy')->insert($adata);
                        }
                    }
                }
            }
            $nouseqid = array_diff($useqids, $updateqids);

            if ($nouseqid) {
                db('Research_question_copy')->where(array('id' => array('in', $nouseqid)))->delete();
            }
//
            $nouseaid = array_diff($useaids, $updateaids);

            if ($nouseaid) {
                db('Research_answer_copy')->where(array('id' => array('in', $nouseaid)))->delete();
            }
            return ajax_info('修改成功！', 'u');

        }

        $data['lang'] = cookie('think_var_admin');
        $res = $this->model->allowField(true)->save($data);
        if ($res) {
            $rid = $this->model->id;

            foreach ($question as $k => $q) {
                if (!isset($option[$k]) || (isset($option[$k]) && empty($option[$k])) || empty($q)) continue;

                $qdata = array('rid' => $rid,'point'=>$point[$k], 'answer' => strtoupper($answer[$k]), 'name' => htmlspecialchars($q), 'type' => isset($ismulti[$k]) ? intval($ismulti[$k]) : 0);
                if (db('Research_question_copy')->insert($qdata)) {
                    $qid = db('Research_question_copy')->getLastInsID();
                    foreach ($option[$k] as $key => $v) {
//                        if (empty($v)) continue;
                        $adata = array('qid' => $qid, 'question' => $oldquestion[$k][$key], 'name' => htmlspecialchars($v));
                        $aid = db('Research_answer_copy')->insert($adata);
                    }
                }
            }

            return ajax_info('保存成功', 'y');
        } else {
            return ajax_info('添加失败');
        }
    }

    /**
     * 删除
     */
    public function del($id)
    {
        $re = $this->model->del($id);
        if ($re) {
            $this->_delcahe();
            $rqdata = db('Research_question_copy')->where(array('rid' => $id))->select();
            $useqids = $useaids = array();
            foreach ($rqdata as $v) {
                $useqids[] = $v['id'];
                $answerobj = db('Research_answer_copy')->where(array('qid' => $v['id']))->order('id asc')->select();
                foreach ($answerobj as $a) {
                    $useaids[] = $a['id'];
                }
            }
            if ($useqids) {
                db('Research_question_copy')->where(array('id' => array('in', $useqids)))->delete();
            }
            if ($useaids) {
                db('Research_answer_copy')->where(array('id' => array('in', $useaids)))->delete();
            }
            ajaxMsg('1', '删除成功');
        } else {
            ajaxMsg('0', '删除成功');
        }

    }

    /**
     * 读取试卷列表
     * @param $id
     */
    public function read($id)
    {
        $order[$this->order] = $this->sort;
        $list = db('research_result_copy')->where('rid', $id)->where($this->datas)->order($order)->paginate()->appends($this->request->param());
        $this->assign('num', db('research_result_copy')->where('rid', $id)->count());

        $this->assign([
                'list' => $list,
            ]
        );
        return $this->fetch();

    }

    /**
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function count($id)
    {
        $list = array();
        $count =null;
        $an = db('research_result_copy')->where('id', $id)->order('id asc')->find();
        $question = db('Research_question_copy')->where(array('rid' => $an['rid']))->order('id asc')->select();
        foreach ($question as $i => $q) {
            $list[$q['id']]['question'] = $q;
            $list[$q['id']]['answer'] = null;
        }

        $answer = json_decode($an['content']);
        if($an['contentscore']){
            $contentscore = json_decode($an['contentscore']);
            foreach ($contentscore as $ki => $va) {
                $list[$ki]['contentscore'] = $va;
            }
        }

        foreach ($answer as $ki => $va) {
            $list[$ki]['answer'] = $va;
            $question =db('research_question_copy')->where('id',$ki)->where('answer',$va)->where('type','neq',2)->value('point');
            $count += $question;
        }

        $type =db('research_question_copy')->where('rid',$an['rid'])->where('type',2)->value('id');

        $this->assign([
            'list' => $list,
            'an' => $an,
            'count' => $count,
            'type' => $type,
        ]);

        return $this->fetch();
    }

    /**
     * 保存考生分数
     * @param $id
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function countsave($score)
    {
        if(is_numeric($score)){
            $param = $this->request->param();
            $date=array(
                'id'=>$param['id'],
                'qid'=>$param['qid'],
            );

            db('research_result_copy')->where($date)->update(array('score'=>$score,'contentscore'=>json_encode($param['contentscore'])));
            return ajax_info('评分成功！', 'u');
        }
        return ajax_info('请填写数字分数！');

    }

    public function delresult($id){
        db('research_result_copy')->where(array('id' => $id))->delete();
        ajaxMsg('1', '删除成功');
    }
}
